/*
 * @Author: bill
 * @Date: 2020-07-13 09:25:33
 * @LastEditTime: 2020-07-13 11:52:10
 * @Description: 
 */ 
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import qs from 'qs';
import _ from 'lodash';
import { getToken } from '@/utils/auth'
import { logout } from '@/api/user'

// create an axios instance
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  // timeout: 5000, // request timeout
  headers: {
    // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
  },
})
// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    if(config.isFormData){
      config.headers['Content-Type'] = 'multipart/form-data; boundary=----WebKitFormBoundary3AKdAWXp5YIqGe3K'
    }
    if (localStorage.getItem('Token')) {
      config.headers['Authorization'] = `Bearer ${localStorage.getItem('Token')}`
    }
    return config
  },
  error => {
    // do something with request error
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    const res = response.data
    // if the custom code is not 20000, it is judged as an error.
    if (res.code != 200) {
      if(res.code == 4399){
          localStorage.removeItem('Token')
          window.location.reload()
      }{
        Message({
          message: res.msg || 'Error',
          type: 'error',
          duration: 5 * 1000
        })
        return Promise.reject(new Error(res.msg || 'Error'))
      }
    } else {
      return res
    }
  },
  error => {
    console.log('err' + error) // for debug
    Message({
      message: error,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
